import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import { Button, Space, Table, Tabs, Tag } from 'antd';

const { TabPane } = Tabs;

const Test = (props) => {
  console.log(props);

  const [tabkey, setTabKey] = useState('1');

  useEffect(() => {
    if (props.location.state && props.location.state.params) {
      const {
        location: { state = {} },
      } = props;
      const { key } = state.params;
      console.log(key);
      setTabKey(key);
      // 即将离开当前页面（刷新或关闭）时触发，路由跳转不触发该方法
      window.onbeforeunload = () => {
        // 清除localtion的state，是会被自动存在sessionStorage里面的，找到相应的props.location.key,移除相应的数据
        sessionStorage.removeItem(`@@History/${props.location.key}`);
      };
    }
    return () => {
      window.onbeforeunload = null;
    };
  }, []);

  const handleToDetails = (record) => {
    // console.log(record)
    history.push('/test/details', {
      params: { key: tabkey, name: record.name },
    });
  };

  const handleTabChange = (key) => {
    setTabKey(key);
  };

  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a href="#">{text}</a>,
    },
    {
      title: 'Age',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: 'Address',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: 'Tags',
      key: 'tags',
      dataIndex: 'tags',
      render: (tags) => (
        <>
          {tags.map((tag) => {
            let color = tag.length > 5 ? 'geekblue' : 'green';
            if (tag === 'loser') {
              color = 'volcano';
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => handleToDetails(record)}>详情 {record.name}</a>
          <a>删除</a>
        </Space>
      ),
    },
  ];

  const data = [
    {
      key: '1',
      name: 'John Brown',
      age: 32,
      address: 'New York No. 1 Lake Park',
      tags: ['nice', 'developer'],
    },
    {
      key: '2',
      name: 'Jim Green',
      age: 42,
      address: 'London No. 1 Lake Park',
      tags: ['loser'],
    },
    {
      key: '3',
      name: 'Joe Black',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
      tags: ['cool', 'teacher'],
    },
  ];

  return (
    <div>
      <Tabs
        defaultActiveKey={tabkey}
        activeKey={tabkey}
        onChange={handleTabChange}
      >
        <TabPane tab="测试" key="1">
          <Button onClick={handleToDetails}>跳转</Button>
        </TabPane>
        <TabPane tab="嘿哈" key="2">
          <Table columns={columns} dataSource={data} />
        </TabPane>
      </Tabs>
    </div>
  );
};

export default Test;
